package com.tang.utils;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.tang.system.vo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

public abstract class BaseController<T extends Object> {
    public abstract IService<T> getService();

    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1", required = false) Integer pageNo,
                       @RequestParam(defaultValue = "10", required = false) Integer pageSize,
                       HttpServletRequest request) {
        QueryWrapper wrapper = QueryUtils.build(request, Object.class);
        IPage page = QueryUtils.createPage(pageNo, pageSize, Object.class);
        return Result.ok(getService().page(page, wrapper));
    }

    @GetMapping("/queryById")
    public Result queryById(String id) {
        if (CommonUtils.isEmpty(id)) return Result.ok();
        return Result.ok(getService().getById(id));
    }

    @DeleteMapping("/setRemoveTagById")
    public Result setRemoveTagById(String id) {
        if (CommonUtils.isEmpty(id)) return Result.ok();
        getService().update().set("del", true).eq("id", id).update();
        return Result.ok();
    }

    @DeleteMapping("/setRemoveTagByIds")
    public Result setRemoveTagByIds(String ids) {
        if (CommonUtils.isEmpty(ids)) return Result.ok();
        getService().update().set("del", true).in("id", Arrays.asList(ids.split(","))).update();
        return Result.ok();
    }

    @DeleteMapping("/removeById")
    public Result removeById(String id) {
        if (CommonUtils.isEmpty(id)) return Result.ok();
        getService().removeById(id);
        return Result.ok();
    }

    @DeleteMapping("/removeByIds")
    public Result removeByIds(String ids) {
        if (CommonUtils.isEmpty(ids)) return Result.ok();
        getService().removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok();
    }

    @DeleteMapping("/save")
    public Result save(@RequestBody T t) {
        Object id = BeanUtil.getProperty(t, "id");
        if (StringUtils.isEmpty(id)) {
            getService().save(t);
        } else {
            getService().updateById(t);
        }
        return Result.ok();
    }
}
